package com.lifo.utils.interceptor;

import com.lifo.utils.PropertiesSingleton;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.lang.Nullable;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Properties;

/**
 * Created by Administrator on 2017/9/19 0019.
 */
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    private static final String LOGINURL = "loginUrl";

    private static  final String USERID = "userId";
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if (!StringUtils.isEmpty(request.getSession().getAttribute(USERID))) {
            return true;
        } else {
            String loginUrl = PropertiesSingleton.newInstance().getProperties().getProperty(LOGINURL);
            log.info("LoginInterceptor==>用户未登陆，即将跳转到登陆页面======>{}", loginUrl);
            response.sendRedirect(loginUrl);
            return false;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {

    }
}
